<script setup>
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'
import { isPC } from '@/utils/flexible'
import { ref, onMounted } from 'vue'
import { getOSSClient } from '@/utils/sts'
import { useStore } from 'vuex'
import { putProfile } from '@/api/sys'
const store = useStore()
const props = defineProps({
  imgBlob: {
    type: String,
    required: true
  }
})
// Cropper对象配置
const MBOptions = {
  viewMode: 1,
  dragMode: 'move',
  aspectRatio: 1,
  cropBoxMovable: false,
  cropBoxResizable: false
}
const PCOptions = {
  aspectRatio: 1
}
const imgRef = ref(null)
let cropper = null
onMounted(() => {
  // 初始化Cropper对象
  cropper = new Cropper(imgRef.value, isPC.value ? PCOptions : MBOptions)
})
// 裁剪后的图片数据
const onButClick = () => {
  cropper.getCroppedCanvas().toBlob((blob) => {
    // 上传到阿里云
    putObjectToOSS(blob)
  })
}
//阿里云验证上传
let ossClient = null
const putObjectToOSS = async (blob) => {
  if (!ossClient) {
    ossClient = await getOSSClient()
  }
  try {
    const fileTypeArr = blob.type.split('/')
    const fileName = `${store.getters.userInfo.username}/${Date.now()}.${
      fileTypeArr[fileTypeArr.length - 1]
    }`
    const res = await ossClient.put(`images/${fileName}`, blob)
    onChangeUrl(res.url)
  } catch (error) {
    console.log('error', error)
  }
}
//关闭对话框
const emits = defineEmits(['close'])

// 向服务器提交图片url
const onChangeUrl = async (url) => { 
  const res = await putProfile({
    ...store.getters.userInfo,
    avatar: url
  })
  store.dispatch('sys/getUserInfo')
  emits('close')
}
</script>
<template>
  <div class="container w-[520px] h-[520px]">
    <img :src="imgBlob" ref="imgRef" class="w-64 h-64" />
    <Button @click="onButClick">确定</Button>
  </div>
</template>

<style lang="scss" scoped></style>
